const express = require("express");
const bodyParser = require("body-parser");
const https = require("https"); 
const app = express();
const cors = require('cors');
const { log } = require("console");
const port = 3000;

// 设置跨域
const corsOptions = {
  origin: '*', 
  credentials: true, 
};

app.use(cors(corsOptions));

app.use(bodyParser.json());

app.options('/chat', (req, res) => {
  res.setHeader('Access-Control-Allow-Methods', 'POST');
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
  res.status(200).end();
});

app.post("/chat", (req, res) => {
  console.log("收到了请求");
  const userMessages = req.body.messages;
  console.log(userMessages);

  // 设置响应头为SSE格式
  res.setHeader('Content-Type', 'text/event-stream');
  res.setHeader('Cache-Control', 'no-cache');
  res.setHeader('Connection', 'keep-alive');

  const options = {
    method: 'POST',
    hostname: 'dashscope.aliyuncs.com',
    path: '/api/v1/services/aigc/text-generation/generation',
    headers: {
      "Content-Type": "application/json",
      "Accept": "text/event-stream",
      "Authorization": "Bearer sk-fw9kVQOJY4",
      "X-DashScope-SSE": "enable",
    },
  };

  const reqStream = https.request(options, (responseStream) => {
    
    // 监听数据事件，接收到的每个数据块立即发送给客户端
    responseStream.on('data', (chunk) => {
      console.log(chunk.toString())
      res.write(chunk.toString());
    });

    // 监听结束事件
    responseStream.on('end', () => {
      res.end();
    });
  });

  reqStream.on('error', (error) => {
    console.error(error);
    res.status(500).send("Internal Server Error");
  });

  // 发送请求体
  reqStream.write(JSON.stringify({
    input: {
      messages: userMessages,
    },
    model: "qwen-turbo",
  }));
  reqStream.end();
});


app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}`);
});
